package no.hist.rtc.rtchatme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import no.hist.rtc.rtchat.R;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class ChatActivity extends Activity {
	
	private String ip_tjener = "10.0.0.2";
	private int portnr = 12345;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
    }
    
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.asdfg, menu);
        return true;
    }
	
    @SuppressLint("NewApi")
    public void onClickSend(View v){
    	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    	StrictMode.setThreadPolicy(policy);
    	String se = ((EditText)findViewById(R.id.melding)).getText().toString();
    	Log.d("TAGG", "sender: " + (se));
    	//new Taske(this, (((EditText)findViewById(R.id.melding)).getText().toString())).start();
    	new AccessWebServiceTask().doInBackground(se);
    }
    

	private class AccessWebServiceTask extends AsyncTask<String, Void, Void>{

		@TargetApi(3)
		protected Void doInBackground(String... params) {
			Socket s 			= null;
	    	PrintWriter out		= null;
	    	BufferedReader in 	= null;
	    	
	    	String se = params[0];
	    	
	        try {
	        	
	        	s = new Socket(ip_tjener, portnr);
	            Log.v("TAG", "C: Connected to server" + s.toString());
	            out = new PrintWriter(s.getOutputStream(), true);
	            in = new BufferedReader(new InputStreamReader(s.getInputStream()));
	            Log.i("Tagg", "blir sendt til tjeneren: " + se);
	            out.println(se);
	            
	        } catch (IOException e) {
	            e.printStackTrace();
	        }finally{//close socket!!
	        	try{
		        	out.close();
		        	in.close();
		        	s.close();
	        	}catch(Exception e){
	        		e.printStackTrace();
	        	}
	        }
	        return null;
		}

	}
}
